// pages/mqttconfig/mqttconfig.js
const mqtt = require('../../utils/mqtt.min.js');
const app = getApp();

Page({
  data: {
    host: 'broker.emqx.io',
    port: '8084',
    username: '',
    password: '',
    clientId: '',
    topic: 'water/level',
    subscribeStatus: '未连接',
    mqttConnected: false,
    isLoggedIn: false,
    hasSubscribed: false
  },

  onLoad() {
    // 初始化页面数据
    this.updateFromGlobalData();
  },

  onShow() {
    // 页面显示时更新数据
    this.updateFromGlobalData();
  },

  // 从全局数据更新页面数据
  updateFromGlobalData() {
    this.setData({
      mqttConnected: app.globalData.mqttConnected,
      isLoggedIn: app.globalData.isLoggedIn,
      hasSubscribed: app.globalData.hasSubscribed
    });
  },

  // 全局数据更新回调
  onGlobalDataUpdate() {
    this.updateFromGlobalData();
  },

  // 输入框事件处理
  onHostInput(e) {
    this.setData({ host: e.detail.value });
  },

  onPortInput(e) {
    this.setData({ port: e.detail.value });
  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  onClientIdInput(e) {
    this.setData({ clientId: e.detail.value });
  },

  onTopicInput(e) {
    this.setData({ topic: e.detail.value });
  },

  // 验证必填输入
  validateInput() {
    if (!this.data.host.trim()) {
      wx.showToast({
        title: '请输入服务器地址',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.topic.trim()) {
      wx.showToast({
        title: '请输入订阅主题',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 连接MQTT服务器
  connectMQTT() {
    if (!this.validateInput()) return;

    const self = this;
    self.setData({ subscribeStatus: '正在连接...' });

    // 生成客户端ID
    const clientId = this.data.clientId || 'miniprogram_' + Math.random().toString(16).substr(2, 8);

    // 配置连接选项
    const options = {
      clientId: clientId,
      username: this.data.username,
      password: this.data.password,
      keepalive: 60,
      clean: true,
      protocolVersion: 4,
      reconnectPeriod: 1000,
      connectTimeout: 30 * 1000,
      timerVariant: 'native'
    };

    // 注意：微信小程序中使用 wxs 协议而不是 wss
    const connectUrl = `wxs://${this.data.host}:${this.data.port}/mqtt`;

    try {
      // 连接MQTT服务器
      const client = mqtt.connect(connectUrl, options);

      // 存储客户端到全局
      app.setMqttClient(client);

      // 连接事件处理
      client.on('connect', function() {
        console.log('MQTT连接成功');
        app.updateMqttStatus(true, false, false);
        self.setData({ subscribeStatus: '连接成功' });

        // 自动订阅主题
        self.doSSubscribe();
      });

      // 消息接收处理
      client.on('message', function(topic, message) {
        const msgStr = message.toString();
        console.log('收到消息:', topic, msgStr);

        let isWarning = false;

        try {
          const msgData = JSON.parse(msgStr);

          if (msgData.hasOwnProperty('msg')) {
            isWarning = msgData.msg === 'true' || msgData.msg === true;
          } else if (msgData.hasOwnProperty('value')) {
            isWarning = msgData.value === 'true' || msgData.value === true;
          } else if (msgData.hasOwnProperty('status')) {
            isWarning = msgData.status === 'true' || msgData.status === true;
          } else if (msgData.hasOwnProperty('warning')) {
            isWarning = msgData.warning === 'true' || msgData.warning === true;
          } else if (msgData.hasOwnProperty('level')) {
            isWarning = msgData.level === 'high' || msgData.level === 'warning';
          } else {
            const jsonStr = JSON.stringify(msgData);
            isWarning = jsonStr.includes('true') || jsonStr.includes('warning') || jsonStr.includes('high');
          }
        } catch (e) {
          console.log('消息不是JSON格式，按字符串处理');
          isWarning = msgStr === 'true' || msgStr === '1' ||
                      msgStr.includes('true') || msgStr.includes('warning');
        }

        app.updateMqttStatus(true, true, isWarning);

        // 如果水位超过警戒线并且用户已订阅，发送微信提醒
        if (isWarning && app.globalData.hasSubscribed) {
					app.GlobalonSendMessageTest();
        }

        // 设备在线检测
        clearTimeout(self.offlineTimer);
        self.offlineTimer = setTimeout(() => {
          app.updateMqttStatus(true, false, isWarning);
        }, 30000);
      });

      // 错误处理
      client.on('error', function(error) {
        console.error('MQTT错误:', error);
        app.updateMqttStatus(false, false, false);
        self.setData({
          subscribeStatus: '连接错误: ' + error.message
        });
      });

      // 关闭连接处理
      client.on('close', function() {
        console.log('MQTT连接关闭');
        app.updateMqttStatus(false, false, false);
        self.setData({
          subscribeStatus: '连接已关闭'
        });
      });

    } catch (error) {
      console.error('MQTT连接异常:', error);
      self.setData({
        subscribeStatus: '连接异常: ' + error.message
      });
    }
  },

  // 执行订阅操作
  doSSubscribe() {
    const client = app.globalData.mqttClient;
    if (!client || !this.data.mqttConnected) {
      this.setData({ subscribeStatus: '请先连接MQTT服务器' });
      return;
    }

    client.subscribe(this.data.topic, { qos: 0 }, (err) => {
      if (err) {
        console.error('订阅失败:', err);
        this.setData({ subscribeStatus: '订阅失败: ' + err.message });
      } else {
        console.log('订阅成功:', this.data.topic);
        this.setData({ subscribeStatus: '已订阅: ' + this.data.topic });

        // 如果已登录，向后端发送订阅请求
        // if (app.globalData.isLoggedIn) {
        //   this.subscribeToBackend();
        // }
      }
    });
  },

  // 向后端订阅提醒
  // subscribeToBackend() {
  //   const token = wx.getStorageSync('token');
  //   wx.request({
  //     url: app.globalData.baseUrl + '/subscriptions/create/',
  //     method: 'POST',
  //     header: {
  //       'Content-Type': 'application/json',
  //       'Authorization': 'Token ' + token
  //     },
  //     data: {
  //       topic: this.data.topic
  //     },
  //     success: () => {
  //       app.globalData.hasSubscribed = true;
  //       wx.showToast({
  //         title: '订阅成功，将接收微信提醒',
  //         icon: 'success'
  //       });
  //     },
  //     fail: (err) => {
  //       console.error('订阅失败:', err);
  //       wx.showToast({
  //         title: '订阅失败',
  //         icon: 'none'
  //       });
  //     }
  //   });
  // },

  // 断开连接
  disconnectMQTT() {
    const client = app.globalData.mqttClient;
    if (client) {
      client.end();
      app.updateMqttStatus(false, false, false);
      this.setData({
        subscribeStatus: '已断开连接'
      });

      wx.showToast({
        title: '已断开连接',
        icon: 'success'
      });
    }
  }
});